package dao

import (
	"context"
	"device-admin/internal/dal"
	"device-admin/internal/models"
)

type QuickReply struct{}

// Add 新增
func (QuickReply) Add(ctx context.Context, query *dal.Query, merchantID, text string) (string, error) {
	qr := dal.QuickReply
	record := &models.QuickReply{
		MerchantID: merchantID,
		Text:       text,
	}
	return record.ID, qr.WithContext(ctx).Create(record)
}

// Update 更新
func (QuickReply) Edit(ctx context.Context, query *dal.Query, merchantID, ID, text string) error {
	qr := dal.QuickReply
	info, err := qr.WithContext(ctx).
		Where(qr.MerchantID.Eq(merchantID)).
		Where(qr.ID.Eq(ID)).
		UpdateSimple(qr.Text.Value(text))
	if info.RowsAffected == 1 && err == nil {
		return nil
	}
	return err
}

// Delete 删除
func (QuickReply) Delete(ctx context.Context, query *dal.Query, merchantID, ID string) error {
	qr := dal.QuickReply
	info, err := qr.WithContext(ctx).
		Where(qr.MerchantID.Eq(merchantID)).
		Where(qr.ID.Eq(ID)).
		Delete(&models.QuickReply{})
	if info.RowsAffected == 1 && err == nil {
		return nil
	}
	return err
}

// Exists 判断记录是否存在
func (QuickReply) Exists(ctx context.Context, query *dal.Query, ID string) bool {
	qr := dal.QuickReply
	count, _ := qr.WithContext(ctx).Where(qr.ID.Eq(ID)).Count()
	return count == 1
}

// List 快捷回复列表
func (QuickReply) List(ctx context.Context, query *dal.Query, merchantID, text string) ([]*models.QuickReply, error) {
	qr := dal.QuickReply
	tx := qr.WithContext(ctx).
		Select(qr.ID, qr.Text).
		Where(qr.MerchantID.Eq(merchantID))
	if text != "" {
		tx = tx.Where(qr.Text.Like("%" + text + "%"))
	}

	list, err := tx.Find()
	if err != nil {
		return []*models.QuickReply{}, err
	}
	return list, nil
}
